package com.zk5_education.Service.Impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.zk5_education.Service.OssService;
import com.zk5_education.untils.ConStanProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endPoint = ConStanProperties.END_POINT;
        String accessKeyId = ConStanProperties.KEY_ID;
        String accessKeySecret = ConStanProperties.KEY_SECRET;
        String bucketName = ConStanProperties.BUCKET_NAME;
        String uploadUrl = null;
        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            //获取上传文件流
            InputStream inputStream = file.getInputStream();
            //构建日期路径：avatar/2019/02/26/文件名
            //文件名：uuid.扩展名
            String filename= file.getOriginalFilename();

            String uuid= UUID.randomUUID().toString().replaceAll("-","");
            filename=uuid+filename;
            String dataPath=new DateTime().toString("yyyy/MM/dd");
            filename=dataPath+"/"+filename;
            //文件上传至阿里云
            ossClient.putObject(bucketName, filename, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //获取url地址
            uploadUrl = "https://" + bucketName + "." + endPoint + "/" + filename;

            System.out.println(uploadUrl);
        } catch (IOException e) {
        }
        return uploadUrl;
    }
}
